package cn.jaye.fabric.controller.rest;

import cn.jaye.fabric.application.ChainCodeApplicationService;
import cn.jaye.fabric.application.command.DeployChainCodeCommand;
import cn.jaye.fabric.application.command.ExecuteChaincodeCommand;
import cn.jaye.fabric.application.command.InfoChainCodeCommand;
import cn.jaye.fabric.common.util.KeyUtil;
import cn.jaye.fabric.common.util.ResultUtil;
import cn.jaye.fabric.domain.model.ChainCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jaye
 * @create 2018-05-25 11:39
 */
@RestController
@RequestMapping("/chaincode")
public class ChainCodeController {

    @Autowired
    private ChainCodeApplicationService chainCodeApplicationService;

    @PostMapping("/list")
    public String list() {
        List<ChainCode> chainCodes = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            String chaincodeId = KeyUtil.getUUID();
            String name = "test";
            String version = "v" + (i + 1);
            String path = "/gopath/test";
            String channelName = "myChannel";
            Integer txCount = 1;
            ChainCode chainCode = new ChainCode(chaincodeId, name, version, path, channelName, txCount);
            chainCodes.add(chainCode);
        }
//        chainCodeApplicationService.list();
        return ResultUtil.success(chainCodeApplicationService.list());
    }

    @PostMapping("/info")
    public String info(InfoChainCodeCommand infoChainCodeCommand) {
        return JSON.toJSONString(chainCodeApplicationService.info(infoChainCodeCommand));
    }

    @PostMapping("/execute")
    public String execute(ExecuteChaincodeCommand executeChaincodeCommand) {
        return JSON.toJSONString(chainCodeApplicationService.execute(executeChaincodeCommand));
    }

    @PostMapping("/install")
    public String install(DeployChainCodeCommand deployChainCodeCommand) {
        return JSON.toJSONString(chainCodeApplicationService.install(deployChainCodeCommand));
    }

    @PostMapping("/instantiate")
    public String instantiate(DeployChainCodeCommand deployChainCodeCommand) {
        return JSON.toJSONString(chainCodeApplicationService.instantiate(deployChainCodeCommand));
    }
}
